package cn.stylefeng.guns.modular.business.frequency.transport.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.enums.CoreExceptionEnum;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.exception.enums.StatusExceptionEnum;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.base.entity.BaseEntity;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.modular.business.custom.enums.*;
import cn.stylefeng.guns.modular.business.frequency.banner.config.activityMq.Producer;
import cn.stylefeng.guns.modular.business.frequency.cmcity.entity.CmCity;
import cn.stylefeng.guns.modular.business.frequency.cmcity.mapper.CmCityMapper;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.model.result.PkgLinkman;
import cn.stylefeng.guns.modular.business.frequency.cmcompanyorder.entity.CmCompanyOrder;
import cn.stylefeng.guns.modular.business.frequency.cmcompanyorder.mapper.CmCompanyOrderMapper;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.mapper.CmDriverMapper;
import cn.stylefeng.guns.modular.business.frequency.cmlinkman.mapper.CmLinkmanMapper;
import cn.stylefeng.guns.modular.business.frequency.finance.mapper.FinanceMapper;
import cn.stylefeng.guns.modular.business.frequency.financedetail.entity.FinanceDetail;
import cn.stylefeng.guns.modular.business.frequency.financedetail.mapper.FinanceDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.financesettlement.entity.FinanceSettlement;
import cn.stylefeng.guns.modular.business.frequency.financesettlement.mapper.FinanceSettlementMapper;
import cn.stylefeng.guns.modular.business.frequency.financetransport.entity.FinanceTransport;
import cn.stylefeng.guns.modular.business.frequency.financetransport.mapper.FinanceTransportMapper;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.mapper.OrderCarVerifyMapper;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.entity.OrderLogistics;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.mapper.OrderLogisticsMapper;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.entity.OrderModifyDetail;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.mapper.OrderModifyDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickCarExcludeDTO;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.entity.OrderStatusChange;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.service.OrderStatusChangeService;
import cn.stylefeng.guns.modular.business.frequency.ordersub.entity.OrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.mapper.OrderSubMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderCarVerify;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderSubBase;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgTransportSimple;
import cn.stylefeng.guns.modular.business.frequency.ordertransportrelation.entity.OrderTransportRelation;
import cn.stylefeng.guns.modular.business.frequency.ordertransportrelation.mapper.OrderTransportRelationMapper;
import cn.stylefeng.guns.modular.business.frequency.syssite.entity.SysSite;
import cn.stylefeng.guns.modular.business.frequency.syssite.mapper.SysSiteMapper;
import cn.stylefeng.guns.modular.business.frequency.transport.entity.Transport;
import cn.stylefeng.guns.modular.business.frequency.transport.enums.TransportExceptionEnum;
import cn.stylefeng.guns.modular.business.frequency.transport.mapper.TransportMapper;
import cn.stylefeng.guns.modular.business.frequency.transport.model.param.TransportDTO;
import cn.stylefeng.guns.modular.business.frequency.transport.model.param.TransportParam;
import cn.stylefeng.guns.modular.business.frequency.transport.model.result.*;
import cn.stylefeng.guns.modular.business.frequency.transport.service.TransportService;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.entity.TransportLevel;
import cn.stylefeng.guns.modular.business.frequency.transportlevel.mapper.TransportLevelMapper;
import cn.stylefeng.guns.modular.business.frequency.transportleveldetail.entity.TransportLevelDetail;
import cn.stylefeng.guns.modular.business.frequency.transportleveldetail.mapper.TransportLevelDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.transportsign.mapper.TransportSignMapper;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.BaseUtils;
import cn.stylefeng.guns.sys.modular.util.SnowIdUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 运单 服务实现类
 *
 * @author yujie
 * @date 2023/05/09 17:15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TransportServiceImpl extends ServiceImpl<TransportMapper, Transport> implements TransportService {

    @Autowired
    private TransportMapper transportMapper;
    @Autowired
    private OrderStatusChangeService orderStatusChangeService;
    @Autowired
    private OrderLogisticsMapper logisticsMapper;
    @Resource
    private FinanceTransportMapper financeTransportMapper;
    @Autowired
    private BusinessUtil businessUtil;
    @Autowired
    private OrderSubMapper orderSubMapper;
    @Resource
    private Producer producer;
    @Autowired
    private OrderCarVerifyMapper orderCarVerifyMapper;
    @Resource
    private FinanceMapper financeMapper;
    @Autowired
    private TransportSignMapper orderSignMapper;
    @Resource
    private FinanceDetailMapper financeDetailMapper;

    @Autowired
    private OrderTransportRelationMapper orderTransportRelationMapper;
    @Resource
    private TransportLevelDetailMapper transportLevelDetailMapper;
    @Resource
    private CmLinkmanMapper linkmanMapper;
    @Autowired
    private CmDriverMapper driverMapper;
    @Autowired
    private SysSiteMapper siteMapper;
    @Autowired
    private CmCompanyOrderMapper companyOrderMapper;
    @Autowired
    private TransportLevelMapper transportLevelMapper;
    @Resource
    private OrderModifyDetailMapper orderModifyDetailMapper;

    @Override
    public PageResult<Transport> page(TransportParam transportParam) {

        // 构造条件
        LambdaQueryWrapper<Transport> queryWrapper = new LambdaQueryWrapper<>();


        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<Transport> list(TransportParam transportParam) {

        // 构造条件
        LambdaQueryWrapper<Transport> queryWrapper = new LambdaQueryWrapper<>();


        return this.list(queryWrapper);
    }

    @Override
    public void add(TransportParam transportParam) {

        // 将dto转为实体
        Transport transport = new Transport();
        BeanUtil.copyProperties(transportParam, transport);


        this.save(transport);
    }

    @Override
    public void delete(TransportParam transportParam) {

        // 根据id查询实体
        Transport transport = this.queryTransport(transportParam);


        // 更新实体
        this.updateById(transport);

    }

    @Override
    public void edit(TransportParam transportParam) {

        // 根据id查询实体
        Transport transport = this.queryTransport(transportParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(transportParam, transport);

        // 不能修改状态，用修改状态接口修改状态
        transport.setStatus(null);

        this.updateById(transport);
    }

    @Override
    public Transport detail(TransportParam transportParam) {
        return this.queryTransport(transportParam);
    }

    @Override
    public void changeStatus(TransportParam transportParam) {
        Long id = transportParam.getId();
        Integer status = transportParam.getStatus();


        // 更新枚举，更新只能更新未删除状态的
        LambdaUpdateWrapper<Transport> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(Transport::getId, id).set(Transport::getStatus, status);
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new ServiceException(StatusExceptionEnum.UPDATE_STATUS_ERROR);
        }
    }

    @Override
    public Page getWaitTransportOrderList(OrderDTO orderDTO) {
        orderDTO.setTenantId(businessUtil.getTenantId());
        Page<PkgOrderSub> page = transportMapper.getWaitTransportOrderList(PageFactory.defaultPage(), orderDTO);
        return page;
    }

    @Override
    public Map<String, List<String>> getStartCodeAndDestinationCode(OrderDTO orderDTO) {
        Map map = new HashMap();
        List<String> startCodes = transportMapper.getStartCodes(orderDTO, businessUtil.getTenantId());
        List<String> destinationCodes = transportMapper.getDestinationCodes(orderDTO, businessUtil.getTenantId());
        map.put("startCodes", startCodes);
        map.put("destinationCodes", destinationCodes);
        return map;
    }

    @Resource
    private CmCityMapper cmCityMapper;


    @Override
    public Page<TransportPageVO> getFinishTransportList(TransportDTO transportDTO) {
        Page<TransportPageVO> finishTransportList = transportMapper.getFinishTransportList(PageFactory.defaultPage(), transportDTO, businessUtil.getTenantId());
        finishTransportList.getRecords().forEach(new Consumer<TransportPageVO>() {
            @Override
            public void accept(TransportPageVO transportPageVO) {

                String line = transportPageVO.getLine();
                if (StringUtils.isBlank(line)) {
                    return;
                }
                String[] split = line.split(",");
                if (split.length == 2) {
                    transportPageVO.setStartCodeName(cmCityMapper.getNameByCode(split[0]));
                    transportPageVO.setDestinationCodeName(cmCityMapper.getNameByCode(split[1]));
                }


            }
        });
        return finishTransportList;
    }

    @Override
    public Page<TransportPageVO> getSignedTransportList(TransportDTO transportDTO) {
        return transportMapper.getSignedTransportList(PageFactory.defaultPage(), transportDTO, businessUtil.getTenantId());
    }

    @Override
    public PkgTransport getTransportDetail(String id, Integer scene, TransportDTO transportDTO) {
        PkgTransport transport = transportMapper.getPkgTransportDetail(id, scene, transportDTO, businessUtil.getTenantId());
        // 分段费用合计处理
        if (transport != null && transport.getTransportLevelList() != null && transport.getTransportLevelList().size() > 0) {
            for (PkgTransportLevel level : transport.getTransportLevelList()) {
                if (level.getReserved() != 1) {
                    sumTransportLevel(level);
                }
            }
        }
        return transport;
    }

    @Override
    public List<TransportExpandVO> getTransportExpandDetail(String id, TransportDTO transportDTO) {
        return transportMapper.getTransportExpandDetail(id, transportDTO, businessUtil.getTenantId());
    }

    @Override
    public TransportVO getTransportVODetail(TransportDTO transportDTO) {
        TransportVO transportVO = transportMapper.getTransportVODetail(transportDTO, businessUtil.getTenantId());
        for (TransportLevelVO level : transportVO.getTransportLevelVOList()) {
            if (level.getTransportLevelDetailList() != null && level.getTransportLevelDetailList().size() > 0) {
                for (TransportLevelDetail tld : level.getTransportLevelDetailList()) {
                    OrderSub orderSub = orderSubMapper.selectById(tld.getOrderId());
                    //tld.setId(order.getId());
                    tld.setOrderSubNo(orderSub.getOrderSubNo());
                    //tld.setSenderName(order.getLinkmanName());
                    //tld.setSenderPhone(order.getLinkmanPhone());
                    tld.setStartCode(orderSub.getStartCode());
                    tld.setDestinationCode(orderSub.getDestinationCode());
                    tld.setCarName(orderSub.getCarName());
                    tld.setVin(orderSub.getVin());
                    tld.setConsigneeName(orderSub.getConsigneeName());
                    tld.setConsigneePhone(orderSub.getConsigneePhone());
                    tld.setDeliveryPayFee(orderSub.getDeliveryPayFee());
                }
            }
        }
        return transportVO;
    }

    @Override
    public List<PkgTransportOrderDetail> getTransportOrderDetail(OrderDTO orderDTO) {
        return transportLevelDetailMapper.getTransportOrderDetail(orderDTO, businessUtil.getTenantId());
    }

    @Override
    public Page<PkgOrderSubBase> getWaitTransportExcludeList(PickCarExcludeDTO pickCarExcludeDTO) {
        Page<PkgOrderSubBase> list = transportMapper.getWaitTransportExcludeList(PageFactory.defaultPage(), pickCarExcludeDTO, businessUtil.getTenantId());
        if (StringUtils.isNotBlank(pickCarExcludeDTO.getTransportId())) {
            // 编辑时添加，需加上当前运单已经移除的子订单
            TransportVO originTransportVO = getTransportVOUpdate(pickCarExcludeDTO.getTransportId());
            // 原来的装车子订单
            List<Long> originOrderIds = getOrderIdListByTransportVO(originTransportVO);
            //差集
            originOrderIds.removeAll(pickCarExcludeDTO.getOrderIds());
            if (originOrderIds.size() > 0) {
                PickCarExcludeDTO ped = new PickCarExcludeDTO();
                ped.setRemoveOrderIds(originOrderIds);
                List<PkgOrderSubBase> removeList = orderSubMapper.getOrderInfos(originOrderIds);
                list.getRecords().addAll(removeList);
            }
        }
        return list;
    }

    @Override
    public boolean checkTransportAdd(TransportVO transportVO, StringBuilder errorMsg) {
        if (null == transportVO) {
            errorMsg.append("发运信息不能为空");
            return false;
        }
        if (transportVO.getSettlementId() == null) {
            errorMsg.append("结算人ID不可为空");
            return false;
        }
        if (transportVO.getTransportLevelVOList() == null || transportVO.getTransportLevelVOList().size() < 1) {
            errorMsg.append("请至少添加一个发车分段！");
            return false;
        }
        // 不是待发运的
        // 计算代收，欠返费用
        boolean hasCollection = false;
        BigDecimal transportFee = BigDecimal.ZERO;
        BigDecimal collectionFee = BigDecimal.ZERO;
        if (transportVO.getTransportLevelVOList() != null && transportVO.getTransportLevelVOList().size() > 0) {
            for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
                if (transportLevelVO.getReserved() != 1 && (transportLevelVO.getTransportLevelDetailList() == null || transportLevelVO.getTransportLevelDetailList().size() < 1)) {
                    errorMsg.append("分段内至少包含一个订单！");
                    return false;
                }
                if (transportLevelVO.getReserved() != 1) {
                    for (TransportLevelDetail td : transportLevelVO.getTransportLevelDetailList()) {
                        int orderStatus = orderSubMapper.getStatusById(td.getOrderId());
                        if (orderStatus != OrderStatusEnum.NOT_DEPART_ORDER.status && orderStatus != OrderStatusEnum.TRANSFERRING_SIGN.status) {
                            errorMsg.append("存在订单状态：" + OrderStatusEnum.getValue(orderStatus) + ",不可发车！");
                            return false;
                        }
                        transportFee = transportFee.add(td.getCost());
                        if (td.getHasCollection() == 1) {
                            hasCollection = true;
                            OrderSub orderSub = orderSubMapper.selectById(td.getOrderId());
                            collectionFee = collectionFee.add(orderSub.getDeliveryPayFee() == null ? BigDecimal.ZERO : orderSub.getDeliveryPayFee());
                        }
                    }
                    // 直交客户不是同一个收货人不可放在同一段
                    if (transportLevelVO.getType() == 2) {
                        List<Long> orderIds = transportLevelVO.getTransportLevelDetailList().stream().map(TransportLevelDetail::getOrderId).collect(Collectors.toList());
                        int count = orderSubMapper.distinctCountConsigneePhone(orderIds);
                        if (count > 1) {
                            errorMsg.append("直交客户分段不能包含多个收货人！");
                            return false;
                        }
                    }
                }
            }
        }
        if (transportVO.getDriverId() == null && StringUtils.isNotBlank(transportVO.getDriverPhone())) {
            if (!Validator.isMobile(transportVO.getDriverPhone())) {
                errorMsg.append("司机电话格式不正确！");
                return false;
            }
        }
        transportVO.setDriverFee(transportFee);
        if (hasCollection) {
            transportVO.setCollectionFee(collectionFee.compareTo(BigDecimal.ZERO) > 0 ? collectionFee : null);
            transportVO.setBackReturnFee(collectionFee.compareTo(BigDecimal.ZERO) > 0 ? collectionFee.subtract(transportFee) : null);
        } else {
            transportVO.setCollectionFee(null);
            transportVO.setBackReturnFee(null);
        }
        // 组装数据
        PkgLinkman pkgLinkman = linkmanMapper.getPkgLinkmanById(transportVO.getSettlementId(), businessUtil.getTenantId());
        transportVO.setSettlementUser(pkgLinkman.getName());
        transportVO.setSettlementPhone(pkgLinkman.getPhone());
        transportVO.setSupplierId(pkgLinkman.getCompanyId());
        transportVO.setCargoCompany(pkgLinkman.getCompanyName());
        return true;
    }

    @Override
    public void transport(TransportVO transportVO) {
        Transport transport = new Transport();
        transport.setId(SnowIdUtils.uniqueLong());
        BeanUtils.copyProperties(transportVO, transport);
        transport.setTenantId(businessUtil.getTenantId());
        // 发运单分段如果都是直交客户，运单状态为待签收
        transport.setStatus(checkAllCustomerStatus(transportVO) ? TransportStatusEnum.WAIT_DELIVERY.status : TransportStatusEnum.TRANSPORTING.status);

        // 运单业务处理
        dealTransportDetail(transportVO, transport);
    }

    @Autowired
    private FinanceSettlementMapper financeSettlementMapper;

    @Override
    public boolean checkTransportUpdate(TransportVO transportVO, StringBuilder errorMsg) {
        if (transportVO == null || transportVO.getId() == null) {
            errorMsg.append("参数错误，运单ID不能为空");
            return false;
        }
        if (transportVO.getSettlementId() == null) {
            errorMsg.append("结算人ID不能为空");
            return false;
        }
        // 至少添加一个发车分段
        if (transportVO.getTransportLevelVOList() == null || transportVO.getTransportLevelVOList().size() < 1) {
            errorMsg.append("请至少添加一个发车分段！");
            return false;
        }
        // 状态判断
        // 1. 运单状态
        TransportVO originTransportVO = getTransportVOUpdate(transportVO.getId().toString());
        if (originTransportVO.getStatus() == TransportStatusEnum.SIGN_FINISHED.status) {
            errorMsg.append("当前状态不可修改，请联系管理员");
            return false;
        }
        // 运单已结算，不可修改
        long settlementCount = financeSettlementMapper.selectCount(new LambdaQueryWrapper<FinanceSettlement>().eq(FinanceSettlement::getTenantId, transportVO.getId()).eq(FinanceSettlement::getStatus, 0));
        if (settlementCount > 0) {
            errorMsg.append("当前运单已结算，不可修改");
            return false;
        }
        // 2. 订单状态
        for (TransportLevelVO levelVO : originTransportVO.getTransportLevelVOList()) {
            if (levelVO.getReserved() != 1 && levelVO.getType() == 2) {
                // 直接客户
                for (TransportLevelDetail levelDetail : levelVO.getTransportLevelDetailList()) {
                    int status = orderSubMapper.getStatusById(levelDetail.getOrderId());
                    if (status != OrderStatusEnum.WAIT_TAKE.status) {
                        errorMsg.append("当前运单不可修改");
                        return false;
                    }
                }
            }
            if (levelVO.getReserved() != 1 && levelVO.getType() != 2) {
                // 网点
                for (TransportLevelDetail levelDetail : levelVO.getTransportLevelDetailList()) {
                    int status = orderSubMapper.getStatusById(levelDetail.getOrderId());
                    if (status != OrderStatusEnum.HAS_DEPART_ORDER.status) {
                        errorMsg.append("当前运单不可修改");
                        return false;
                    }
                }
            }
        }

        // 不是待发运的
        if (transportVO.getTransportLevelVOList() != null && transportVO.getTransportLevelVOList().size() > 0) {
            for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
                if (transportLevelVO.getReserved() != 1 && (transportLevelVO.getTransportLevelDetailList() == null || transportLevelVO.getTransportLevelDetailList().size() < 1)) {
                    errorMsg.append("分段内至少包含一个订单！");
                    return false;
                }
                // 直交客户不是同一个收货人不可放在同一段
                if (transportLevelVO.getReserved() != 1 && transportLevelVO.getType() == 2) {
                    List<Long> orderIds = transportLevelVO.getTransportLevelDetailList().stream().map(TransportLevelDetail::getOrderId).collect(Collectors.toList());
                    int count = orderSubMapper.distinctCountConsigneePhone(orderIds);
                    if (count > 1) {
                        errorMsg.append("直交客户分段不能包含多个收货人！");
                        return false;
                    }
                }
            }
        }
        // 组装数据
        PkgLinkman pkgLinkman = linkmanMapper.getPkgLinkmanById(transportVO.getSettlementId(), businessUtil.getTenantId());
        transportVO.setSettlementUser(pkgLinkman.getName());
        transportVO.setSettlementPhone(pkgLinkman.getPhone());
        transportVO.setSupplierId(pkgLinkman.getCompanyId());
        transportVO.setCargoCompany(pkgLinkman.getCompanyName());
        return true;
    }

    private List<Long> getLevelIdListByTransportVO(TransportVO transportVO) {
        List<Long> levelIds = new ArrayList<>();
        for (TransportLevelVO levelVO : transportVO.getTransportLevelVOList()) {
            if (levelVO.getId() != null) {
                levelIds.add(levelVO.getId());
            }
        }
        return levelIds;
    }


    @Override
    public void updateTran(TransportVO transportVO) {
        // 2021.9.10 增加订单修改明细
        List<OrderModifyDetail> orderModifyDetails = new ArrayList<>();
        Long operator = LoginContextHolder.me().getSysLoginUserId();
        // 2021.3.3根据当前人能看到的子订单修改
        TransportVO originTransportVO = getTransportVOUpdate(transportVO.getId().toString());
        // 原来的装车子订单 order_id
        List<Long> originOrderIds = getOrderIdListByTransportVO(originTransportVO);
        List<Long> originOrderIdListBak = new ArrayList<>(originOrderIds);
        // 现在的装车分段Ids transport_level id
        List<Long> nowLevelIds = getLevelIdListByTransportVO(transportVO);
        // 现在的装车子订单  order_id
        List<Long> nowOrderIds = getOrderIdListByTransportVO(transportVO);
        // 直交客户的订单删除到付的FinanceDetail
        // 所有直交客户的idList
        List<Long> rectangularCustomerOrderIds = transportLevelDetailMapper.getRectangularCustomerOrderIds(transportVO.getId(), originOrderIds);
        if (rectangularCustomerOrderIds != null && rectangularCustomerOrderIds.size() > 0) {
            for (Long orderId : rectangularCustomerOrderIds) {
                financeMapper.clearDeliveryCollectionInfo(orderId);
                financeDetailMapper.deleteByOrderIdAndType(orderId, FinanceTypeEnum.DELIVERY.type);
            }
        }
        // 运单状态
        //transport.setStatus(checkAllCustomerStatus(transportVO) ? TransportStatusEnum.WAIT_DELIVERY.status : TransportStatusEnum.TRANSPORTING.status);
//        transportMapper.update(transport, new QueryWrapper<Transport>().lambda().eq(Transport::getId, transportVO.getId()));
        // 删除运单订单关联表
        for (Long orderId : originOrderIds) {
            orderTransportRelationMapper.deleteByTransportIdAndOrderId(transportVO.getId().toString(), orderId);
        }
        // 获取修改内容--放在删除分段之前
        try {
            getOrderModifyDetail(orderModifyDetails, transportVO, originTransportVO, originOrderIdListBak);
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
        // 订单状态
        for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
            if (transportLevelVO != null && transportLevelVO.getReserved() != 1) {
                for (TransportLevelDetail tld : transportLevelVO.getTransportLevelDetailList()) {
                    // 订单状态修改
                    // 是否为新装的车
                    if (originOrderIdListBak.contains(tld.getOrderId())) {
                        // 修改的车
                        // 是否修改了分段的交付方式
                        TransportLevel originLevelType = transportLevelMapper.getLevelByTransportIdAndOrderId(transportVO.getId(), tld.getOrderId());
                        if (originLevelType.getType() == 2) {
                            // 直交客户改非直交客户
                            if (transportLevelVO.getType() != 2) {
                                // 未交付的状态改为运输中
                                orderSubMapper.updateStatusById(tld.getOrderId(), OrderStatusEnum.HAS_DEPART_ORDER.status, OrderStatusEnum.WAIT_TAKE.status);
                            }
                        } else {
                            // 非直交客户改直交客户
                            if (transportLevelVO.getType() == 2) {
                                orderSubMapper.updateStatusById(tld.getOrderId(), OrderStatusEnum.WAIT_TAKE.status, OrderStatusEnum.HAS_DEPART_ORDER.status);
                            }
                        }
                    } else {
                        // 新装的车
                        // 如果是直接客户的订单状态为待送车待交付
                        if (transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
                            orderSubMapper.updateStatusById(tld.getOrderId(), OrderStatusEnum.WAIT_TAKE.status, null);
                        } else {
                            orderSubMapper.updateStatusById(tld.getOrderId(), OrderStatusEnum.HAS_DEPART_ORDER.status, null);
                        }
                    }
                }
            }
        }
        // 各分段中子订单信息删除
        // 2021.3.3修改
        for (TransportLevelVO levelVO : originTransportVO.getTransportLevelVOList()) {
            if (levelVO != null && levelVO.getId() != null && levelVO.getTransportLevelDetailList().size() > 0) {
                transportLevelDetailMapper.deleteByLevelId(levelVO.getId());
            }
            // 2021.3.22修改
            // 如果原来的分段删除了
            if (levelVO != null && levelVO.getId() != null) {
                if (!nowLevelIds.contains(levelVO.getId())) {
                    transportLevelMapper.deleteById(levelVO.getId());
                }
            }
        }

        // 财务信息删除 FinanceTransport FinanceDetail
        // 2021.3.3修改
        for (Long orderId : originOrderIds) {
            financeTransportMapper.deleteByTransportIdAndOrderId(transportVO.getId(), orderId);
            financeDetailMapper.deleteByOrderIdAndRelationId(transportVO.getId(), orderId);
        }
        // 去除的子订单列表
        originOrderIds.removeAll(nowOrderIds);
        if (originOrderIds.size() > 0) {
            for (Long orderId : originOrderIds) {
                // 子订单状态还原
                // 该子订单有没有签收，
                int orderSignCount = orderSignMapper.countByOrderId(orderId);
                if (orderSignCount == 0) {
                    // 待发运
                    orderSubMapper.updateStatusById(orderId, OrderStatusEnum.NOT_DEPART_ORDER.status, null);
                } else {
                    // 中转待发
                    orderSubMapper.updateStatusById(orderId, OrderStatusEnum.TRANSFERRING_SIGN.status, null);
                }
                // 2021.9.10 移除的子订单增加修改明细
                orderModifyDetails.add(new OrderModifyDetail(Long.valueOf(orderId), transportVO.getId(), "id", "从运单移除", "", transportVO.getTransportNo(), operator, originTransportVO.getTransportNo()));
            }
        }

        // 2021.9.10 增加订单修改明细
        if (orderModifyDetails.size() > 0) {
            for (OrderModifyDetail orderModifyDetail : orderModifyDetails) {
                orderModifyDetail.setTransportId(businessUtil.getTenantId());
                orderModifyDetailMapper.insert(orderModifyDetail);
            }
        }

        // 分段交付单信息删除
        transportLevelMapper.clearFileUrlByTransportId(transportVO.getId());
        // 修改发运单
        updateTransport(transportVO);
    }

    @Override
    public boolean checkTransportCancel(String id, StringBuilder errorMsg) {

        Transport transport = transportMapper.selectOne(new QueryWrapper<Transport>().lambda().eq(Transport::getId, id));
        if (transport == null || transport.getStatus() == TransportStatusEnum.SIGN_FINISHED.status) {
            errorMsg.append("当前运单不可取消，请联系管理员！");
            return false;
        }
        // 非管理员角色，如果包含多个用户创建的途经点，则不可取消
        if (!LoginContextHolder.me().isTenantAdmin()) {
            int count = transportLevelMapper.countDistinctCreateUser(id);
            if (count > 1) {
                errorMsg.append("该运单包含其他用户创建的途经点，您没有权限取消该运单，请联系管理员");
                return false;
            }
        }

        // 状态判断
        // 1. 运单状态
        TransportVO originTransportVO = getTransportVOUpdate(id);
        // TODO: 2023/6/16  检查发生的原因是否与订单发生的原因有关
        if (ObjectUtil.isNull(originTransportVO)) {
            errorMsg.append("当前运单不存在！");
            return false;
        }
        if (originTransportVO.getStatus() == TransportStatusEnum.SIGN_FINISHED.status) {
            errorMsg.append("当前状态不可取消，请联系管理员");
            return false;
        }
        // 2. 订单状态
        for (TransportLevelVO levelVO : originTransportVO.getTransportLevelVOList()) {
            if (levelVO.getReserved() != 1 && levelVO.getType() == 2) {
                // 直接客户
                for (TransportLevelDetail levelDetail : levelVO.getTransportLevelDetailList()) {
                    int status = orderSubMapper.getStatusById(levelDetail.getOrderId());
                    if (status != OrderStatusEnum.WAIT_TAKE.status) {
                        errorMsg.append("当前运单不可取消");
                        return false;
                    }
                }
            }
            if (levelVO.getReserved() != 1 && levelVO.getType() != 2) {
                // 网点
                for (TransportLevelDetail levelDetail : levelVO.getTransportLevelDetailList()) {
                    int status = orderSubMapper.getStatusById(levelDetail.getOrderId());
                    if (status != OrderStatusEnum.HAS_DEPART_ORDER.status) {
                        errorMsg.append("当前运单不可取消");
                        return false;
                    }
                }
            }
        }
        // 其中一个子订单被签收，则不可取消
        /*List<PkgWxTransportOrderInfo> list = transportMapper.getTransportOrderStatusList(id);
        for (PkgWxTransportOrderInfo order : list) {
            if (order.getStatus() != OrderStatusEnum.HAS_DEPART_ORDER.status) {
                errorMsg.setErrorMsg("当前运单存在子订单" + order.getOrderSubNo() + "，状态不可取消！");
                return false;
            }
        }*/
        // 承运费已经结算的不可取消
        List<FinanceDetail> financeDetails = financeDetailMapper.selectList(new QueryWrapper<FinanceDetail>().lambda().eq(FinanceDetail::getRelationId, id));
        for (FinanceDetail financeDetail : financeDetails) {
            if (financeDetail.getHasSettlement() != null && financeDetail.getHasSettlement().compareTo(BigDecimal.ZERO) > 0) {
                errorMsg.append("运单存在已经结算的承运费，不可取消！");
                return false;
            }
        }
        return true;
    }

    @Override
    public void cancel(String id) {
        // 1.运单状态
        transportMapper.updateStatusById(id, TransportStatusEnum.HAS_CANCEL.status, null);
        // 2.子订单状态还原
        List<PkgWxTransportOrderInfo> list = transportMapper.getTransportOrderStatusList(id);
        for (PkgWxTransportOrderInfo order : list) {
            // 如果子订单之前的发运次数（不包括本次）> 0，则是中转待发，否则为待发运
            if (transportMapper.countOrderTransportNotInclude(order.getOrderId(), id) > 0) {
                orderSubMapper.updateStatusById(order.getOrderId(), OrderStatusEnum.TRANSFERRING_SIGN.status, null);
            } else {
                orderSubMapper.updateStatusById(order.getOrderId(), OrderStatusEnum.NOT_DEPART_ORDER.status, null);
            }
        }
        // 财务承运费明细删除
        financeDetailMapper.deleteByRelationId(id);
        financeTransportMapper.deleteByTransportId(id);
    }

    @Override
    public boolean checkReservedTransport(TransportVO transportVO, StringBuilder errorMsg) {
        if (transportVO == null || transportVO.getId() == null) {
            errorMsg.append("参数错误！发运单ID不能为空");
            return false;
        }
        // 至少一个分段
        if (transportVO.getTransportLevelVOList() == null || transportVO.getTransportLevelVOList().size() < 1) {
            errorMsg.append("请至少添加一个发车分段！");
            return false;
        }

        // 计算总的运费和代收费用
        BigDecimal totalDriverFee = BigDecimal.ZERO;
        BigDecimal totalCollectionFee = BigDecimal.ZERO;
        // 不是待发运的
        if (transportVO.getTransportLevelVOList() != null && transportVO.getTransportLevelVOList().size() > 0) {
            for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
                if (transportLevelVO.getReserved() != 1 && (transportLevelVO.getTransportLevelDetailList() == null || transportLevelVO.getTransportLevelDetailList().size() < 1)) {
                    errorMsg.append("分段内至少包含一个订单！");
                    return false;
                }
                if (transportLevelVO.getReserved() != 1) {
                    for (TransportLevelDetail td : transportLevelVO.getTransportLevelDetailList()) {
                        OrderSub orderSub = orderSubMapper.selectById(td.getOrderId());
                        if (orderSub.getStatus() != OrderStatusEnum.NOT_DEPART_ORDER.status && orderSub.getStatus() != OrderStatusEnum.TRANSFERRING_SIGN.status) {
                            errorMsg.append("订单号D" + orderSub.getOrderSubNo() + "状态：" + OrderStatusEnum.getValue(orderSub.getStatus()) + ",不可发车！");
                            return false;
                        }
                        totalDriverFee = totalDriverFee.add(td.getCost());
                        if (td.getHasCollection() == 1) {
                            totalCollectionFee = totalCollectionFee.add(orderSub.getDeliveryPayFee());
                        }
                    }
                    // 直交客户不是同一个收货人不可放在同一段
                    if (transportLevelVO.getType() == 2) {
                        List<Long> orderIds = transportLevelVO.getTransportLevelDetailList().stream().map(TransportLevelDetail::getOrderId).collect(Collectors.toList());
                        int count = orderSubMapper.distinctCountConsigneePhone(orderIds);
                        if (count > 1) {
                            errorMsg.append("直交客户分段不能包含多个收货人！");
                            return false;
                        }
                    }
                }
            }
        }
        transportVO.setDriverFee(totalDriverFee);
        transportVO.setCollectionFee(totalCollectionFee);
        // 组装数据
        PkgLinkman pkgLinkman = linkmanMapper.getPkgLinkmanById(transportVO.getSettlementId(), businessUtil.getTenantId());
        transportVO.setSettlementUser(pkgLinkman.getName());
        transportVO.setSettlementPhone(pkgLinkman.getPhone());
        transportVO.setSupplierId(pkgLinkman.getCompanyId());
        transportVO.setCargoCompany(pkgLinkman.getCompanyName());
        return true;
    }

    @Override
    public void reservedTransport(TransportVO transportVO) {
        // 运单原线路
        String originLine = transportMapper.getLineById(transportVO.getId());
        List<String> originLineCodeList = new ArrayList<>(Arrays.asList(originLine.split(",")));
        // 运单费用修改
        Transport transport = transportMapper.selectOne(new QueryWrapper<Transport>().lambda().eq(Transport::getId, transportVO.getId()));
        transport.setCollectionFee(transport.getCollectionFee() == null ? BigDecimal.ZERO : transport.getCollectionFee()
                .add(transportVO.getCollectionFee() == null ? BigDecimal.ZERO : transportVO.getCollectionFee()));
        transport.setDriverFee(transport.getDriverFee() == null ? BigDecimal.ZERO : transport.getDriverFee()
                .add(transportVO.getDriverFee() == null ? BigDecimal.ZERO : transportVO.getDriverFee()));
        if (transportVO.getCollectionFee() != null && transportVO.getCollectionFee().compareTo(BigDecimal.ZERO) > 0) {
            // 司机欠返 = 代收 - 运费
            transport.setBackReturnFee(transport.getCollectionFee().subtract(transport.getDriverFee()));
        }
        // 运单状态修改 2021.04.09
        if (transport.getStatus() == TransportStatusEnum.WAIT_DELIVERY.status && hasNeedSign(transportVO)) {
            // 原来是待交付状态，并且本次装车有到达网点的，则需要将运单状态变更为运输中
            transport.setStatus(TransportStatusEnum.TRANSPORTING.status);
        }
        if (transportVO.getTransportLevelVOList() != null && transportVO.getTransportLevelVOList().size() > 0) {
            for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
                // --装车目的地添加到线路中 2021.3.2
                String levelStartCode = "";
                if (transportLevelVO.getReserved() == 0) {
                    levelStartCode = dealTransportLevelStartCode(transportLevelVO.getTransportLevelDetailList().get(0).getOrderId());
                }
                String levelDestinationCode = getLevelDestinationCode(transportLevelVO);
                if (!originLineCodeList.contains(levelDestinationCode)) {
                    // 现有路线中没有新装车路线
                    originLineCodeList.add(levelDestinationCode);
                }

                //将现有的预留版位状态改为已到达
                TransportLevel oldTransportLevel = new TransportLevel();
                oldTransportLevel.setSiteId(businessUtil.getSiteId());
                oldTransportLevel.setTransportId(transportVO.getId());
                transportLevelMapper.updateStatus(oldTransportLevel);
                // --end
                TransportLevel transportLevel = new TransportLevel();
                BeanUtils.copyProperties(transportLevelVO, transportLevel);
                transportLevel.setTransportId(transportVO.getId());
                transportLevel.setStartCode(levelStartCode);
                transportLevel.setSettlementType(transportLevelVO.getSettlementType());
                transportLevel.setDestinationCode(levelDestinationCode);
                //添加结算人
                //网点垫付
                if (transportLevelVO.getSettlementType() != null && transportLevelVO.getSettlementType() == 2) {
                    transportLevel.setSettlementId(LoginContextHolder.me().getSysLoginUserId());
                    transportLevel.setSettlementPhone(LoginContextHolder.me().getSysLoginUser().getPhone());
                    transportLevel.setSettlementName(LoginContextHolder.me().getSysLoginUser().getName());
                    transportLevel.setSiteId(businessUtil.getSiteId());
                } else {
                    //直交客户或者公司垫付
                    transportLevel.setSettlementId(transportVO.getSettlementId());
                    transportLevel.setSettlementPhone(transportVO.getSettlementPhone());
                    transportLevel.setSettlementName(transportVO.getSettlementUser());
                }


                transportLevelMapper.insert(transportLevel);
                if (transportLevelVO.getTransportLevelDetailList() != null && transportLevelVO.getTransportLevelDetailList().size() > 0) {
                    for (TransportLevelDetail tld : transportLevelVO.getTransportLevelDetailList()) {
                        tld.setLevelId(transportLevel.getId());
                        // 运单分段出发地 到达地
                        tld.setStartCode(dealTransportLevelStartCode(tld.getOrderId()));
                        tld.setDestinationCode(levelDestinationCode);
                        tld.setTenantId(businessUtil.getTenantId());
                        // 保存
                        transportLevelDetailMapper.insert(tld);
                        // 订单状态修改
                        int orderStatus = transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.CUSTOMER.type ?
                                OrderStatusEnum.WAIT_TAKE.status : OrderStatusEnum.HAS_DEPART_ORDER.status;
                        orderSubMapper.updateStatusById(tld.getOrderId(), orderStatus, null);
                        //订单发运信息关系存储
                        OrderTransportRelation otr = new OrderTransportRelation(tld.getOrderId(), transportVO.getId(), businessUtil.getTenantId());
                        orderTransportRelationMapper.insert(otr);
                        // 1.财务应付
                        // 财务承运费基础数据插入
                        saveFinanceDetail(tld, transport.getId(), transportLevelVO.getType(), transportLevelVO.getSettlementType(),
                                transportLevel.getSiteId(), transportLevel.getSettlementName(), transportLevel.getSettlementPhone(), transportLevel.getSettlementId());
                        // activemq通知下游系统计算发车奖金
                        producer.sendBonus(BonusTypeEnum.TRANSPORT.type, tld.getOrderId(), LoginContextHolder.me().getSysLoginUserId(), null);
                    }
                }
            }
            transport.setLine(StringUtils.join(originLineCodeList, ","));
            transportMapper.update(transport, new UpdateWrapper<Transport>().lambda().eq(Transport::getId, transportVO.getId()));
        }
    }

    @Override
    public List<PkgTransport> getOrderTransportDetail(String orderId) {
        return transportMapper.getOrderTransportDetail(orderId);
    }

    @Override
    public boolean checkMultiDriverAssign(Transport transport, StringBuilder errorMsg) {
        if (transport == null || transport.getId() == null) {
            errorMsg.append("缺少运单数据");
            return false;
        }
        if (transport.getDriverId() == null) {
            // 没有选择司机
            if (StringUtils.isBlank(transport.getDriverName()) || StringUtils.isBlank(transport.getDriverPhone())) {
                errorMsg.append("司机信息不能为空");
                return false;
            } else if (!Validator.isMobile(transport.getDriverPhone())) {
                errorMsg.append("司机电话格式不正确！");
                return false;
            }
        }
        return true;
    }

    @Override
    public void assignDriver(Transport transport) {
        Transport t = transportMapper.selectOne(new QueryWrapper<Transport>().lambda().eq(Transport::getId, transport.getId()));
        t.setDriverId(transport.getDriverId());
        t.setDriverName(transport.getDriverName());
        t.setDriverPhone(transport.getDriverPhone());
        t.setDriverCardNumber(transport.getDriverCardNumber());

        // 运单信息更新
        transportMapper.update(t, new QueryWrapper<Transport>().lambda().eq(Transport::getId, transport.getId()));
        // 司机任务更新

    }

    @Override
    public List getTransportOrderExport(String levelId) {
        List<TransportOrderExport> list = transportMapper.getTransportOrderExport(levelId, businessUtil.getTenantId());
        return list;
    }

    @Override
    public PkgTransportLevel getTransportLevelDetail(String levelId) {
        PkgTransportLevel level = transportLevelMapper.getPkgTransportLevelById(levelId);
        if (1 != level.getReserved()) {
            sumTransportLevel(level);
        }
        // 运单信息
        PkgTransportSimple transportSimple = transportMapper.getPkgTransportSimpleById(level.getTransportId());
        level.setTransport(transportSimple);
        // 子订单信息
        if (level.getTransportLevelDetailList() != null && level.getTransportLevelDetailList().size() > 0) {
            for (TransportLevelDetail levelDetail : level.getTransportLevelDetailList()) {
                BigDecimal deliveryPayFee = levelDetail.getDeliveryPayFee() == null ? BigDecimal.ZERO : levelDetail.getDeliveryPayFee();
                // 单台订单欠返费用
                levelDetail.setBackReturnFee(levelDetail.getHasCollection() == 1 ? deliveryPayFee.subtract(levelDetail.getCost()) : BigDecimal.ZERO);
                // 验车信息
                PkgOrderCarVerify carVerify = orderCarVerifyMapper.getPkgOrderCarVerify(levelDetail.getOrderId());
                levelDetail.setOrderCarVerify(carVerify);
            }
        }
        return level;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void returnTransport(Long orderId) {
        OrderStatusChange changeServiceOne = orderStatusChangeService.getOne(new QueryWrapper<OrderStatusChange>().lambda()
                .eq(OrderStatusChange::getOrderId, orderId).orderByDesc(BaseEntity::getCreateTime).last("limit 1"));
        if (changeServiceOne == null || !(changeServiceOne != null && ("直交客户发运".equals(changeServiceOne.getRemark()) || "发运".equals(changeServiceOne.getRemark())))) {
            throw new CustomException(CoreExceptionEnum.ORDER_CHANGE_STAGE_ERROR);
        }
        OrderSub orderSub = new OrderSub();
        orderSub.setId(orderId);
        orderSub.setStatus(changeServiceOne.getBeforeChangeStatus());
        //获取最新的运单详情记录
        TransportLevelDetail transportLevelDetail = transportLevelDetailMapper.selectOne(new QueryWrapper<TransportLevelDetail>().lambda()
                .eq(TransportLevelDetail::getOrderId, orderId)
                .orderByDesc(TransportLevelDetail::getCreateTime).last("limit 1"));
        if (transportLevelDetail != null) {
            //查询该途经点是否还存在其他订单
            Integer count = transportLevelDetailMapper.selectCount(new QueryWrapper<TransportLevelDetail>().lambda()
                    .eq(TransportLevelDetail::getLevelId, transportLevelDetail.getLevelId())
                    .notIn(TransportLevelDetail::getId, transportLevelDetail.getId()));
            //途经点无其他订单,删除途经点
            if (count == 0) {
                TransportLevel transportLevel = transportLevelMapper.selectById(transportLevelDetail.getLevelId());
                if (transportLevel != null) {
                    //查询运单是否存在其他途经点
                    Integer selectCount = transportLevelMapper.selectCount(new QueryWrapper<TransportLevel>().lambda().eq(TransportLevel::getTransportId, transportLevel.getTransportId())
                            .notIn(TransportLevel::getId, transportLevel.getId()));
                    if (selectCount == 0) {
                        transportMapper.delete(new QueryWrapper<Transport>().lambda().eq(Transport::getId, transportLevel.getTransportId()));
                        logisticsMapper.delete(new QueryWrapper<OrderLogistics>().lambda().eq(OrderLogistics::getTransportId, transportLevel.getTransportId()));
                    }
                    transportLevelMapper.deleteById(transportLevel);
                }
            }
            transportLevelDetailMapper.deleteById(transportLevelDetail.getId());
        }
        //修改订单状态
        orderSubMapper.updateStatusById(orderId, changeServiceOne.getBeforeChangeStatus(), changeServiceOne.getAfterChangeStatus());
        //删除公司订单
        companyOrderMapper.delete(new QueryWrapper<CmCompanyOrder>().lambda().eq(CmCompanyOrder::getOrderId, orderId));
        //删除订单状态跟踪记录
        orderStatusChangeService.removeById(changeServiceOne.getId());


    }


    @Autowired
    private CmCityMapper cityMapper;
    @Override
    public List<TransportExportVO> getFinishTransportList2(TransportDTO transportDTO) {
        List<TransportPageVO> list = transportMapper.getFinishTransportList2(transportDTO);
        Map<String, CmCity> cityMap = cityMapper.getAllCityMap();
        List<TransportExportVO> exportList = new ArrayList<>();
        list.forEach(item -> {
            TransportExportVO vo = new TransportExportVO();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(DateUtil.formatDateTime(item.getCreateTime()));
            vo.setTransportType(item.getTransportType() == 1 ? "公路运输":"铁路运输");
            // 路线
            if (StringUtils.isNotBlank(item.getLine())) {
                List<String> cityList = new ArrayList<>();
                for (String s : item.getLine().split(",")) {
                    CmCity city = cityMap.get(s);
                    if (city != null) {
                        cityList.add(city.getName());
                    }
                }
                vo.setLine(String.join("-", cityList));
            }
            exportList.add(vo);
        });
        return exportList;
    }


    private boolean hasNeedSign(TransportVO transportVO) {
        boolean hasNeedSign = false;
        for (TransportLevelVO levelVO : transportVO.getTransportLevelVOList()) {
            if (levelVO.getReserved() == 1 || levelVO.getType() != TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
                hasNeedSign = true;
            }
        }
        return hasNeedSign;
    }


    private void updateTransport(TransportVO transportVO) {
        if (transportVO.getTransportLevelVOList() != null && transportVO.getTransportLevelVOList().size() > 0) {
            boolean firstStartCode = true;
            for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
                TransportLevel transportLevel = new TransportLevel();
                BeanUtils.copyProperties(transportLevelVO, transportLevel);
                transportLevel.setTransportId(transportVO.getId());
                if (transportLevelVO.getReserved() == 0 && transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
                    // 直交客户的分段信息取订单收货人信息
                    OrderSub orderSub = orderSubMapper.selectById(transportLevelVO.getTransportLevelDetailList().get(0).getOrderId());
                    transportLevel.setReceiveUser(orderSub.getConsigneeName());
                    transportLevel.setReceivePhone(orderSub.getConsigneePhone());
                    transportLevel.setReceiveAddress(orderSub.getTakeAddress());
                }
                if (transportLevel.getId() != null) {
                    // 更新
                    transportLevelMapper.updateById(transportLevel);
                } else {
                    // 新增
                    transportLevel.setTenantId(businessUtil.getTenantId());
                    transportLevelMapper.insert(transportLevel);
                }

                if (transportLevelVO.getTransportLevelDetailList() != null && transportLevelVO.getTransportLevelDetailList().size() > 0) {
                    boolean firstDestinationCode = true;
                    for (TransportLevelDetail tld : transportLevelVO.getTransportLevelDetailList()) {
                        tld.setLevelId(transportLevel.getId());
                        // 运单分段出发地 到达地
                        // 上一次发运
                        String startCode = dealTransportLevelStartCode(tld.getOrderId());
                        String destinationCode = getLevelDestinationCode(transportLevelVO);
                        tld.setStartCode(startCode);
                        tld.setDestinationCode(destinationCode);
                        tld.setCreateTime(new Date());
                        transportLevelDetailMapper.insert(tld);
                        //订单发运信息关系存储
                        saveOrderTransportRelation(tld.getOrderId(), transportVO.getId());
                        // 1.财务应付
                        // 财务承运费基础数据插入
                        saveFinanceDetail(tld, transportVO.getId(), transportLevelVO.getType(), transportLevelVO.getSettlementType(),
                                transportLevelVO.getSiteId(), transportVO.getSettlementUser(), transportVO.getSettlementPhone(), transportVO.getSettlementId());
                    }
                }
            }
        }
        // 线路 运费，欠返重新计算
        reCalculateLineAndFee(transportVO);
        // 更新运单
        Transport transport = new Transport();
        BeanUtils.copyProperties(transportVO, transport);
        transportMapper.update(transport, new QueryWrapper<Transport>().lambda().eq(Transport::getId, transportVO.getId()));
    }

    private void reCalculateLineAndFee(TransportVO transportVO) {
        TransportDTO transportDTO = new TransportDTO();
        transportDTO.setTransportId(transportVO.getId().toString());
        TransportVO transport = transportMapper.getTransportVODetail(transportDTO, businessUtil.getTenantId());
        // 运单状态
        transportVO.setStatus(checkAllCustomerStatus(transport) ? TransportStatusEnum.WAIT_DELIVERY.status : TransportStatusEnum.TRANSPORTING.status);
        //PkgTransport transport = transportMapper.getPkgTransportDetail(transportVO.getId());
        boolean hasCollection = false;
        boolean firstStartCode = true;
        BigDecimal transportFee = BigDecimal.ZERO;
        BigDecimal collectionFee = BigDecimal.ZERO;
        Set<String> lineCodeList = new LinkedHashSet<>();
        for (TransportLevelVO level : transport.getTransportLevelVOList()) {
            // 预留板位路线信息
            if (level.getReserved() == 1) {
                // 预留板位取预留板位的网点地
                lineCodeList.add(siteMapper.selectById(level.getSiteId()).getRegionCode());
            } else {
                // 取第一个订单的到达地
                if (firstStartCode) {
                    lineCodeList.add(level.getTransportLevelDetailList().get(0).getStartCode());
                    firstStartCode = false;
                }
                lineCodeList.add(level.getTransportLevelDetailList().get(0).getDestinationCode());
            }
            if (level.getTransportLevelDetailList() != null && level.getTransportLevelDetailList().size() > 0) {
                for (TransportLevelDetail detail : level.getTransportLevelDetailList()) {
                    transportFee = transportFee.add(detail.getCost());
                    if (detail.getHasCollection() == 1) {
                        hasCollection = true;
                        OrderSub orderSub = orderSubMapper.selectById(detail.getOrderId());
                        collectionFee = collectionFee.add(orderSub.getDeliveryPayFee() == null ? BigDecimal.ZERO : orderSub.getDeliveryPayFee());
                    }
                }
            }
        }
        transportVO.setLine(String.join(",", lineCodeList));
        transportVO.setDriverFee(transportFee);
        transportVO.setCollectionFee(collectionFee);
        if (hasCollection) {
            transportVO.setBackReturnFee(collectionFee.subtract(transportFee));
        } else {
            transportVO.setBackReturnFee(BigDecimal.ZERO);
        }
    }

    public void getOrderModifyDetail(List<OrderModifyDetail> orderModifyDetails, TransportVO transportVO, TransportVO originTransportVO, List<Long> originOrderIdListBak) {
        Long userId = LoginContextHolder.me().getSysLoginUserId();
        for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
            if (transportLevelVO != null && transportLevelVO.getReserved() != 1 && transportLevelVO.getId() == null) {
                // 记录分段信息修改
                TransportLevel oldLevel = transportLevelMapper.selectById(transportLevelVO.getId());
                //修改结算人
                //网点垫付
                if (transportLevelVO.getSettlementType() != null && transportLevelVO.getSettlementType() == 2) {
                    transportLevelVO.setSettlementId(LoginContextHolder.me().getSysLoginUserId());
                    transportLevelVO.setSettlementPhone(LoginContextHolder.me().getSysLoginUser().getPhone());
                    transportLevelVO.setSettlementName(LoginContextHolder.me().getSysLoginUser().getName());
                    transportLevelVO.setSiteId(businessUtil.getSiteId());
                } else {
                    //公司垫付或者直交客户
                    transportLevelVO.setSettlementId(transportVO.getSettlementId());
                    transportLevelVO.setSettlementPhone(transportVO.getSettlementPhone());
                    transportLevelVO.setSettlementName(transportVO.getSettlementUser());
                }

                for (TransportLevelDetail tld : transportLevelVO.getTransportLevelDetailList()) {
                    TransportLevelDetail oldTld = transportLevelDetailMapper.getByLevelIdAndOrderId(oldLevel.getId(), tld.getOrderId());
                    if (originOrderIdListBak.contains(tld.getOrderId())) {
                        // 修改的车记录修改内容，新装的车不记录
                        // 发运成本
                        if (!BaseUtils.compareDecimal(tld.getCost(), oldTld.getCost())) {
                            FinanceDetail fd = financeDetailMapper.getByOrderIdAndRelationId(8, oldTld.getOrderId(), transportVO.getId());
                            if (fd.getHasSettlement().compareTo(BigDecimal.ZERO) > 0) {
                                throw new CustomException("财务已经结算的订单不可修改发运成本");
                            }
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "cost", "发运成本", tld.getCost().toString(), oldTld.getCost().toString(), userId, originTransportVO.getTransportNo()));
                        }
                        // 是否代收
                        if (BaseUtils.neCompareTwo(tld.getHasCollection(), oldTld.getHasCollection())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "has_collection", "是否代收", YesOrNoEnum.getValue(tld.getHasCollection()), YesOrNoEnum.getValue(oldTld.getHasCollection()), userId, originTransportVO.getTransportNo()));
                        }
                        // 交付方式
                        if (BaseUtils.neCompareTwo(transportLevelVO.getType(), oldLevel.getType())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "type", "分段交付方式", TransportLevelDeliveryTypeEnum.getValue(transportLevelVO.getType()), TransportLevelDeliveryTypeEnum.getValue(oldLevel.getType()), userId, originTransportVO.getTransportNo()));
                        }
                        // siteId
                        if (BaseUtils.neCompareTwo(transportLevelVO.getSiteId(), oldLevel.getSiteId())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "site_id", "交付网点",
                                    transportLevelVO.getSiteId() == null ? "" : siteMapper.getNameById(transportLevelVO.getSiteId()),
                                    oldLevel.getSiteId() == null ? "" : siteMapper.getNameById(oldLevel.getSiteId()),
                                    userId, originTransportVO.getTransportNo()));
                        }
                        // 承运类型
                        if (BaseUtils.neCompareTwo(transportVO.getType(), originTransportVO.getType())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "type", "承运类型", TransportTypeEnum.getValue(transportVO.getType()), TransportTypeEnum.getValue(originTransportVO.getType()), userId, originTransportVO.getTransportNo()));
                        }
                        // 承运公司
                        if (BaseUtils.neCompareTwo(transportVO.getCargoCompany(), originTransportVO.getCargoCompany())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "cargo_company", "承运公司", transportVO.getCargoCompany(), originTransportVO.getCargoCompany(), userId, originTransportVO.getTransportNo()));
                        }
                        // 结算人
                        if (BaseUtils.neCompareTwo(transportLevelVO.getSettlementName(), oldLevel.getSettlementName())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "settlement_user", "承运结算人", transportLevelVO.getSettlementName(), oldLevel.getSettlementName(), userId, originTransportVO.getTransportNo()));
                        }
                        // 司机
                        if (BaseUtils.neCompareTwo(transportVO.getDriverName(), originTransportVO.getDriverName())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "driver_name", "承运司机", transportVO.getDriverName(), originTransportVO.getDriverName(), userId, originTransportVO.getTransportNo()));
                        }
                        // 司机电话
                        if (BaseUtils.neCompareTwo(transportVO.getDriverPhone(), originTransportVO.getDriverPhone())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "driver_phone", "承运司机电话", transportVO.getDriverPhone(), originTransportVO.getDriverPhone(), userId, originTransportVO.getTransportNo()));
                        }
                        // 大板车牌
                        if (BaseUtils.neCompareTwo(transportVO.getLicensePlateNumber(), originTransportVO.getLicensePlateNumber())) {
                            orderModifyDetails.add(new OrderModifyDetail(oldTld.getOrderId(), transportVO.getId(), "license_plate_number", "大板车牌", transportVO.getLicensePlateNumber(), originTransportVO.getLicensePlateNumber(), userId, originTransportVO.getTransportNo()));
                        }
                    }
                }
            }
        }
    }


    /**
     * 处理发运逻辑
     */
    private void dealTransportDetail(TransportVO transportVO, Transport transport) {
        transport.setId(SnowIdUtils.uniqueLong());
        // 物流信息
        OrderLogistics logistics = new OrderLogistics();
        logistics.setTenantId(businessUtil.getTenantId());
        logistics.setType(2);
        logistics.setArriveLocation("已装车" + "  " + transportVO.getCargoCompany());
        logistics.setTransportId(transport.getId());
        logisticsMapper.insert(logistics);
        // 司机是否需要保存
        // --------------END-----------------------------------
        List<String> lineCodeList = new ArrayList<>();
        if (transportVO.getTransportLevelVOList() != null && transportVO.getTransportLevelVOList().size() > 0) {
            boolean firstStartCode = true;
            for (TransportLevelVO transportLevelVO : transportVO.getTransportLevelVOList()) {
                // 分段到达地
                String levelDestinationCode = getLevelDestinationCode(transportLevelVO);
                String levelStartCode = "";
                if (!lineCodeList.contains(levelDestinationCode)) {
                    lineCodeList.add(levelDestinationCode);
                }
                if (transportLevelVO.getReserved() == 0) {
                    levelStartCode = dealTransportLevelStartCode(transportLevelVO.getTransportLevelDetailList().get(0).getOrderId());
                }

                TransportLevel transportLevel = new TransportLevel();
                BeanUtils.copyProperties(transportLevelVO, transportLevel);
                transportLevel.setTenantId(businessUtil.getTenantId());
                transportLevel.setTransportId(transport.getId());
                //网点垫付
                if (transportLevelVO.getSettlementType() != null && transportLevelVO.getSettlementType() == 2) {
                    transportLevel.setSettlementId(LoginContextHolder.me().getSysLoginUserId());
                    transportLevel.setSettlementPhone(LoginContextHolder.me().getSysLoginUser().getPhone());
                    transportLevel.setSettlementName(LoginContextHolder.me().getSysLoginUser().getName());
                } else {
                    transportLevel.setSettlementId(transportVO.getSettlementId());
                    transportLevel.setSettlementPhone(transportVO.getSettlementPhone());
                    transportLevel.setSettlementName(transportVO.getSettlementUser());
                }

                if (isLevelCustomerType(transportLevelVO.getReserved(), transportLevelVO.getType())) {
                    // 直交客户的分段信息取订单收货人信息
                    OrderSub orderSub = orderSubMapper.selectById(transportLevelVO.getTransportLevelDetailList().get(0).getOrderId());
                    transportLevel.setReceiveUser(orderSub.getConsigneeName());
                    transportLevel.setReceivePhone(orderSub.getConsigneePhone());
                    transportLevel.setReceiveAddress(orderSub.getTakeAddress());
                }
                transportLevel.setSettlementType(transportLevelVO.getSettlementType());
                transportLevel.setStartCode(levelStartCode);
                transportLevel.setDestinationCode(levelDestinationCode);
                transportLevel.setTenantId(businessUtil.getTenantId());
                transportLevelMapper.insert(transportLevel);

                if (transportLevelVO.getTransportLevelDetailList() != null && transportLevelVO.getTransportLevelDetailList().size() > 0) {
                    for (TransportLevelDetail tld : transportLevelVO.getTransportLevelDetailList()) {
                        // 分段到达地的订单 交易信息
                        tld.setLevelId(transportLevel.getId());
                        // 运单分段出发地
                        String levelDetailStartCode = dealTransportLevelStartCode(tld.getOrderId());
                        if (firstStartCode) {
                            lineCodeList.add(0, levelDetailStartCode);
                            firstStartCode = false;
                        }
                        tld.setStartCode(levelDetailStartCode);
                        tld.setTenantId(businessUtil.getTenantId());
                        tld.setDestinationCode(levelDestinationCode);
                        transportLevelDetailMapper.insert(tld);

                        //添加订单到下一个目的地不是订单的目的地，添加中转签收提醒
                        //如果运单目的地和网点目的地一样,到达欠收,不一样,中专签收
                        OrderSub orderSubBak = orderSubMapper.selectById(tld.getOrderId());
                        if (!ObjectUtil.equal(orderSubBak.getDestinationCode(), levelDestinationCode)) {
                            // 中转签收
                            businessUtil.addMessage(String.format("%s  %s中转签收提醒", orderSubBak.getCarName(), orderSubBak.getVin()), "你有一个中转签收订单，请及时处理", orderSubBak, 3);
                        } else {
                            // 到达签收
                            businessUtil.addMessage(String.format("%s  %s到达签收提醒", orderSubBak.getCarName(), orderSubBak.getVin()), "你有一个到达签收订单，请及时处理", orderSubBak, 4);
                        }
                        // 订单状态修改
                        int orderStatus = transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.CUSTOMER.type ?
                                OrderStatusEnum.WAIT_TAKE.status : OrderStatusEnum.HAS_DEPART_ORDER.status;

                        //记录订单状态变化
                        String remark = transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.CUSTOMER.type ?
                                "直交客户发运" : "发运";
                        OrderSub orderSub = orderSubMapper.selectById(tld.getOrderId());
                        orderStatusChangeService.saveOrderStatusChange(orderSub.getStatus(), orderStatus, tld.getOrderId(), remark);
                        orderSubMapper.updateStatusById(tld.getOrderId(), orderStatus, null);
                        //订单发运信息关系存储
                        saveOrderTransportRelation(tld.getOrderId(), transport.getId());
                        // 1.财务信息保存
                        // 财务承运费基础数据插入
                        saveFinanceDetail(tld, transport.getId(), transportLevelVO.getType(), transportLevelVO.getSettlementType(), transportLevel.getSiteId(),
                                transportLevel.getSettlementName(), transportLevel.getSettlementPhone(), transportLevel.getSettlementId());

                        // 企业通讯录订单保存
                        CmCompanyOrder companyOrder = new CmCompanyOrder(
                                transport.getSupplierId()
                                , transport.getSettlementId()
                                , tld.getOrderId()
                                , 3, tld.getCost(), null, new Date()
                                , transport.getDriverName(), transport.getDriverPhone(), businessUtil.getTenantId());
                        companyOrderMapper.insert(companyOrder);
                        // activemq通知下游系统计算发车奖金
                        producer.sendBonus(BonusTypeEnum.TRANSPORT.type, tld.getOrderId(), LoginContextHolder.me().getSysLoginUserId(), null);
                    }
                }
            }
        }
        transport.setLine(String.join(",", lineCodeList));
        transportMapper.insert(transport);
    }

    private boolean isLevelCustomerType(Integer reserved, Integer type) {
        return reserved == 0 && type == TransportLevelDeliveryTypeEnum.CUSTOMER.type;
    }

    @Transactional
    public void saveFinanceDetail(TransportLevelDetail tld, Long transportId, Integer levelType, Integer settlementType,
                                  Long siteId, String settlementUser, String settlementPhone, Long settlementId) {
        FinanceTransport ft = new FinanceTransport();
        ft.setOrderId(tld.getOrderId());
        ft.setTransport(tld.getCost());
        ft.setTransportHas(BigDecimal.ZERO);
        ft.setTransportUn(tld.getCost());
        ft.setTransportId(transportId);
        ft.setTransportSettlementType(1);
        FinanceDetail fd = new FinanceDetail();
        fd.setOrderId(tld.getOrderId());
        fd.setRelationId(transportId);
        fd.setType(FinanceTypeEnum.TRANSPORT.type);
        fd.setNeedSettlement(tld.getCost());
        fd.setHasSettlement(BigDecimal.ZERO);
        fd.setUnSettlement(tld.getCost());
        // 结算人为承运商
        fd.setSettlementUser(settlementUser);
        fd.setSettlementPhone(settlementPhone);
        fd.setSettlementUserId(settlementId);
        ft.setTransportSettlementName(settlementUser);
        ft.setTransportSettlementPhone(settlementPhone);
        financeDetailMapper.insert(fd);
        financeTransportMapper.insert(ft);

        // 直交客户到付应收
        if (levelType == TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
            OrderSub orderSub = orderSubMapper.selectById(tld.getOrderId());
            if (orderSub.getDeliveryPayFee() != null && orderSub.getDeliveryPayFee().compareTo(BigDecimal.ZERO) > 0) {
                // 直交客户，结算人承运商
                financeMapper.updateDeliveryInfo(tld.getOrderId(), settlementUser, settlementPhone);
                // 解决订单欠付改到付financeDetail 已经存在记录，只是结算人是空
                FinanceDetail financeDetail = financeDetailMapper.getByOrderIdAndType(tld.getOrderId(), 2);
                if (financeDetail == null) {
                    FinanceDetail deliveryFd = new FinanceDetail();
                    deliveryFd.setOrderId(tld.getOrderId());
                    deliveryFd.setType(FinanceTypeEnum.DELIVERY.type);
                    deliveryFd.setSettlementUserId(settlementId);
                    deliveryFd.setSettlementUser(settlementUser);
                    deliveryFd.setSettlementPhone(settlementPhone);
                    deliveryFd.setNeedSettlement(orderSub.getDeliveryPayFee());
                    deliveryFd.setUnSettlement(orderSub.getDeliveryPayFee());
                    deliveryFd.setHasSettlement(BigDecimal.ZERO);
                    financeDetailMapper.insert(deliveryFd);
                } else {
                    financeDetail.setSettlementUser(settlementUser);
                    financeDetail.setSettlementUserId(settlementId);
                    financeDetail.setSettlementPhone(settlementPhone);
                    financeDetailMapper.updateSettlementUserInfo(tld.getOrderId(), 2, settlementUser, settlementPhone, settlementId);
                }
                // ----------END-------------------------------------
            }
        }
    }
//    SAAS 代码,蒋志宇说代码错误,现在替换成上面的那个
//    public void saveFinanceDetail(TransportLevelDetail tld, Long transportId, Integer levelType, Integer settlementType,
//                                  Long siteId, String settlementUser, String settlementPhone, Long settlementId) {
//        FinanceTransport ft = new FinanceTransport();
//        ft.setOrderId(tld.getOrderId());
//        ft.setTransport(tld.getCost());
//        ft.setTransportHas(BigDecimal.ZERO);
//        ft.setTransportUn(tld.getCost());
//        ft.setTransportId(transportId);
//        ft.setTransportSettlementType(1);
//        ft.setTenantId(businessUtil.getTenantId());
//        FinanceDetail fd = new FinanceDetail();
//        fd.setOrderId(tld.getOrderId());
//        fd.setRelationId(transportId);
//        fd.setType(FinanceTypeEnum.TRANSPORT.type);
//        fd.setNeedSettlement(tld.getCost());
//        fd.setHasSettlement(BigDecimal.ZERO);
//        fd.setUnSettlement(tld.getCost());
//        fd.setSettlementType(settlementType);
//        fd.setTenantId(businessUtil.getTenantId());
//        // 公司付款
//        // 结算人
//        fd.setSettlementUser(settlementUser);
//        fd.setSettlementPhone(settlementPhone);
//        fd.setSettlementUserId(settlementId);
//        ft.setTransportSettlementName(settlementUser);
//        ft.setTransportSettlementPhone(settlementPhone);
//        ft.setTransportSettlementUserId(settlementId);
//        fd.setSettlementSiteId(siteId);
//        fd.setTransportId(transportId);
//        financeDetailMapper.insert(fd);
//        financeTransportMapper.insert(ft);
//
//        // 直交客户到付应收
//        if (levelType == TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
//            OrderSub orderSub = orderSubMapper.selectById(tld.getOrderId());
//            if (orderSub.getDeliveryPayFee() != null && orderSub.getDeliveryPayFee().compareTo(BigDecimal.ZERO) > 0) {
//                // 直交客户，结算人承运商
//                financeMapper.updateDeliveryInfo(tld.getOrderId(), settlementUser, settlementPhone);
//                FinanceDetail deliveryFd = new FinanceDetail();
//                deliveryFd.setOrderId(tld.getOrderId());
//                deliveryFd.setType(FinanceTypeEnum.DELIVERY.type);
//                deliveryFd.setSettlementUserId(settlementId);
//                deliveryFd.setSettlementUser(settlementUser);
//                deliveryFd.setSettlementPhone(settlementPhone);
//                deliveryFd.setSettlementType(settlementType);
//                deliveryFd.setNeedSettlement(orderSub.getDeliveryPayFee());
//                deliveryFd.setUnSettlement(orderSub.getDeliveryPayFee());
//                deliveryFd.setHasSettlement(BigDecimal.ZERO);
//                deliveryFd.setTenantId(businessUtil.getTenantId());
//                financeDetailMapper.insert(deliveryFd);
//            }
//        }
//    }


    private void saveOrderTransportRelation(Long orderId, Long transportId) {
        OrderTransportRelation otr = new OrderTransportRelation();
        otr.setOrderId(orderId);
        otr.setTransportId(transportId);
        otr.setTenantId(businessUtil.getTenantId());
        orderTransportRelationMapper.insert(otr);
    }

    /**
     * 获取子订单在该运单的出发地
     *
     * @param
     */
    private String dealTransportLevelStartCode(Long orderId) {
        StringBuilder sb = new StringBuilder();
        TransportLevelDetail lastTld = transportLevelDetailMapper.getLastTransportLevelDetail(orderId);
        if (lastTld != null) {
            sb.append(lastTld.getDestinationCode());
        } else {
            sb.append(orderSubMapper.getOrderStartCode(orderId));
        }
        return sb.toString();
    }

    private List<Long> getOrderIdListByTransportVO(TransportVO transportVO) {
        List<Long> orderIds = new ArrayList<>();
        transportVO.getTransportLevelVOList().forEach(levelVO -> {
            if (levelVO.getReserved() != 1 && levelVO.getTransportLevelDetailList().size() > 0) {
                levelVO.getTransportLevelDetailList().forEach(y -> orderIds.add(y.getOrderId()));
            }
        });
        return orderIds;
    }


    /**
     * 获取分段的到达地
     *
     * @param transportLevelVO
     * @return
     */
    private String getLevelDestinationCode(TransportLevelVO transportLevelVO) {
        StringBuilder sb = new StringBuilder();
        if (transportLevelVO.getReserved() == 1 || transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.SITE.type
                || transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.NEAR_SITE.type) {
            // 预留板位 || 网点 || 网点附近
            SysSite site = siteMapper.selectById(transportLevelVO.getSiteId());
            sb.append(site.getRegionCode());
        } else if (transportLevelVO.getReserved() == 0 && transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
            // 直交客户取子订单的目的地
            String orderDes = orderSubMapper.getOrderDestinationCode(transportLevelVO.getTransportLevelDetailList().get(0).getOrderId());
            sb.append(orderDes);
        } else if (transportLevelVO.getReserved() == 0 && transportLevelVO.getType() == TransportLevelDeliveryTypeEnum.NO_SITE_TRANSFER.type) {
            // 无网点中转
            sb.append(transportLevelVO.getTransferCityCode());
        }
        return sb.toString();
    }

    /**
     * 是否所有分段都是直接客户
     *
     * @param transportVO
     * @return
     */
    private boolean checkAllCustomerStatus(TransportVO transportVO) {
        for (TransportLevelVO levelVO : transportVO.getTransportLevelVOList()) {
            if (levelVO.getType() != TransportLevelDeliveryTypeEnum.CUSTOMER.type) {
                return false;
            }
        }
        return true;
    }

    private TransportVO getTransportVOUpdate(String id) {
        // 数据范围权限，只能看到自己发运的段信息
        TransportDTO transportDTO = new TransportDTO();
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        transportDTO.setTransportId(id);

        transportDTO.setDataList(empByOrgList);
        TransportVO transportVO = transportMapper.getTransportVODetail(transportDTO, businessUtil.getTenantId());

        return transportVO;
    }


    /**
     * 计算分段的承运费、代收、欠返费用合计
     *
     * @param level
     */
    private void sumTransportLevel(PkgTransportLevel level) {
        BigDecimal totalTransportFee = BigDecimal.ZERO;
        BigDecimal totalCollectionFee = BigDecimal.ZERO;
        BigDecimal totalDeliveryPayFee = BigDecimal.ZERO;
        for (TransportLevelDetail levelDetail : level.getTransportLevelDetailList()) {
            BigDecimal deliveryPayFee = levelDetail.getDeliveryPayFee() == null ? BigDecimal.ZERO : levelDetail.getDeliveryPayFee();
            totalTransportFee = totalTransportFee.add(levelDetail.getCost());
            totalDeliveryPayFee = totalDeliveryPayFee.add(deliveryPayFee);
            if (levelDetail.getHasCollection() == 1) {
                totalCollectionFee = totalCollectionFee.add(deliveryPayFee);
            }
        }
        level.setDriverFee(totalTransportFee);
        level.setCollectionFee(totalCollectionFee);
        level.setDeliveryPayFee(totalDeliveryPayFee);
        level.setBackReturnFee(totalCollectionFee.compareTo(BigDecimal.ZERO) > 0 ? totalCollectionFee.subtract(totalTransportFee) : BigDecimal.ZERO);
    }


    /**
     * 获取运单
     *
     * @author yujie
     * @since 2023/05/09 17:15
     */
    private Transport queryTransport(TransportParam transportParam) {
        Transport transport = this.getById(transportParam.getId());
        if (ObjectUtil.isEmpty(transport)) {
            throw new ServiceException(TransportExceptionEnum.NOT_EXISTED);
        }
        return transport;
    }
}